package com.zhz.project.main.bmc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.zhz.project.dal.dataobject.TocBmc;

public class BmcTransfer extends DefaultHandler {

	// 以下是期刊的信息
	private String identifier;
	private boolean identifierBoolean;
	private StringBuffer identifier_sb = new StringBuffer();

	private String datestamp;
	private boolean datestampBoolean;
	private StringBuffer datestamp_sb = new StringBuffer();

	private List<String> setSpec = new ArrayList<String>();;

	private List<String> creator = new ArrayList<String>();

	private String title;
	private boolean titleBoolean;
	private StringBuffer title_sb = new StringBuffer();

	private String description;
	private boolean descriptionBoolean;
	private StringBuffer description_sb = new StringBuffer();

	private String publisher;
	private boolean publisherBoolean;
	private StringBuffer publisher_sb = new StringBuffer();

	private String date;
	private boolean dateBoolean;
	private StringBuffer date_sb = new StringBuffer();

	private String type;
	private boolean typeBoolean;
	private StringBuffer type_sb = new StringBuffer();

	private String dc_identifier;
	private boolean dc_identifierBoolean;
	private StringBuffer dc_identifier_sb = new StringBuffer();

	private String language;
	private boolean languageBoolean;
	private StringBuffer language_sb = new StringBuffer();

	private String content;
	private int count;

	// 解析器的回调事件，元素开始，
	public void startElement(String uri, String localName, String rawName,
			Attributes attrs) throws SAXException {
		if (rawName.equals("identifier")) {
			// identifier = content;
			identifierBoolean = true;
		} else if (localName.equals("datestamp")) {
			// datestamp = content;
			datestampBoolean = true;
		} else if (localName.equals("title")) {
			// title = content;
			titleBoolean = true;
		} else if (localName.equals("description")) {
			// description = content;
			descriptionBoolean = true;
		} else if (localName.equals("publisher")) {
			// publisher = content;
			publisherBoolean = true;
		} else if (localName.equals("date")) {
			// date = content;
			dateBoolean = true;
		} else if (localName.equals("type")) {
			// type = content;
			typeBoolean = true;
		} else if (rawName.equals("dc:identifier")) {
			// dc_identifier = content;
			dc_identifierBoolean = true;
		} else if (localName.equals("language")) {
			// language = content;
			languageBoolean = true;
		}
	}

	// 解析器的回调事件，元素结束，
	public void endElement(String uri, String localName, String rawName)
			throws SAXException {
		// System.out.println("-----");
		if (localName.equals("record")) {
			// System.out.println("一条记录结束，输出全部信息，然后清空变量值!");
			TocBmc bmc = new TocBmc();
			bmc.setIdentifier(identifier);
			identifier_sb.delete(0, identifier_sb.length());
			bmc.setDatestamp(datestamp);
			datestamp_sb.delete(0, datestamp_sb.length());
			bmc.setTitle(title);
			title_sb.delete(0, title_sb.length());
			bmc.setPublisher(publisher);
			publisher_sb.delete(0, publisher_sb.length());
			bmc.setDate(date);
			date_sb.delete(0, date_sb.length());
			bmc.setLanguage(language);
			language_sb.delete(0, language_sb.length());
			bmc.setDescription(description);
			description_sb.delete(0, description_sb.length());
			bmc.setType(type);
			type_sb.delete(0, type_sb.length());
			bmc.setDcIdentifier(dc_identifier);
			dc_identifier_sb.delete(0, dc_identifier_sb.length());
			if (creator.size() > 0)

				bmc.setCreator(creator.get(0));
			if (creator.size() > 0)
				bmc.setSetSpec(setSpec.get(0));
			++count;

			// baseDao.save(bmc);

		} else if (localName.equals("header")) {
			// nothing to do
		} else if (localName.equals("datestamp")) {
			datestamp = datestamp_sb.toString().replaceAll("\r\n", "")
					.replaceAll("\\s{2,}", " ");
			datestampBoolean = false;
		} else if (localName.equals("metadata")) {
			// nothing to do
		} else if (localName.equals("dc")) {
			// nothing to do
		} else if (localName.equals("title")) {
			title = title_sb.toString().replaceAll("\r\n", "").replaceAll(
					"\\s{2,}", " ");
			titleBoolean = false;
		} else if (localName.equals("publisher")) {
			publisher = publisher_sb.toString().replaceAll("\r\n", "")
					.replaceAll("\\s{2,}", " ");
			publisherBoolean = false;
		} else if (localName.equals("date")) {
			date = date_sb.toString().replaceAll("\r\n", "").replaceAll(
					"\\s{2,}", " ");
			dateBoolean = false;
		} else if (localName.equals("language")) {
			language = language_sb.toString().replaceAll("\r\n", "")
					.replaceAll("\\s{2,}", " ");
			languageBoolean = false;
		} else if (localName.equals("creator")) {
			creator.add(content);
		} else if (localName.equals("setSpec")) {
			setSpec.add(content);
		} else if (localName.equals("description")) {
			description = description_sb.toString().replaceAll("\r\n", "")
					.replaceAll("\\s{2,}", " ");
			descriptionBoolean = false;
		} else if (localName.equals("type")) {
			type = type_sb.toString().replaceAll("\r\n", "").replaceAll(
					"\\s{2,}", " ");
			typeBoolean = false;
		} else if (rawName.equals("identifier")) {
			identifier = identifier_sb.toString().replaceAll("\r\n", "")
					.replaceAll("\\s{2,}", " ");
			identifierBoolean = false;
		} else if (rawName.equals("dc:identifier")) {
			dc_identifier = dc_identifier_sb.toString().replaceAll("\r\n", "")
					.replaceAll("\\s{2,}", " ");
			dc_identifierBoolean = false;
		}
		// System.out.println("---");
	}

	public void characters(char[] ch, int start, int end) throws SAXException {
		content = new String(ch, start, end);

		if (identifierBoolean)
			identifier_sb.append(content);
		if (datestampBoolean)
			datestamp_sb.append(content);
		if (titleBoolean)
			title_sb.append(content);
		if (descriptionBoolean)
			description_sb.append(content);
		if (publisherBoolean)
			publisher_sb.append(content);
		if (dateBoolean)
			date_sb.append(content);
		if (typeBoolean)
			type_sb.append(content);
		if (dc_identifierBoolean)
			dc_identifier_sb.append(content);
		if (languageBoolean)
			language_sb.append(content);

	}

	public void parse(SAXParser sp, InputSource s) {

		try {
			sp.parse(s, this);

		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	public void go() {
		for (int i = 1; i < 145; i++) {
			String passedXML = BmcTransfer.readFileByLines("F:/bmc/bmc-" + i
					+ ".txt");
			System.out.println("F:/bmc/bmc-" + i + ".txt	" + count);
			try {
				// SAX解析机制…………
				SAXParserFactory factory = SAXParserFactory.newInstance();
				factory.setNamespaceAware(true);
				factory.setFeature("http://xml.org/sax/features/namespaces",
						true);
				factory.setFeature(
						"http://xml.org/sax/features/namespace-prefixes", true);
				SAXParser saxParser = factory.newSAXParser();

				InputSource s = new InputSource(new StringReader(passedXML));
				parse(saxParser, s);

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}

	}

	public static void main(String[] args) {
		BmcTransfer bt = new BmcTransfer();
		bt.go();
	}

	/**
	 * 以行为单位读取文件，常用于读面向行的格式化文件
	 * 
	 * @param fileName
	 *            文件名
	 */
	public static String readFileByLines(String fileName) {
		File file = new File(fileName);
		BufferedReader reader = null;
		StringBuffer sb = new StringBuffer();
		try {
			reader = new BufferedReader(new FileReader(file));
			String str = null;
			// 一次读入一行，直到读入null为文件结束
			while ((str = reader.readLine()) != null) {
				sb.append(str).append("\r\n");
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		return sb.toString();
	}
}
